#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include "tree.h"

char menu(void);
void addpet(Tree *pt);
void droppet(Tree *pt);
void showpets(const Tree *pt);
void findpet(const Tree *pt);
void printitem(Item item);
void uppercase(char *str);
char *s_gets(char *st, int n);

int main(){
	Tree pets;
	char choice;
	InitTree(&pets);
	while((choice=menu()) != 'q'){
		switch(choice){
			case 'a':addpet(&pets);break;
			case 'l':showpets(&pets);break;
			case 'f':findpet(&pets);break;
			case 'n':printf("%d pets in club\n",TreeCount(&pets));break;
			case 'd':droppet(&pets);break;
			default:puts("Switching error");
		}
	}
	DeleteAll(&pets);
	puts("Bye!");
	return 0;
}
char menu(void){
	int ch;
	puts("Enter the choice:");
	puts("a)add a pet l)show list of pets");
	puts("n)number of pets f)find pets");
	puts("d)delte a pet q)quit");
	while((ch=getchar())!=EOF){
		while(getchar()!='\n')continue;
		ch = tolower(ch);
		if(strchr("alfndq",ch)==NULL)puts("Please enter an a,l,f,n,d,or q:");
		else break;
	}
	if(ch == EOF)ch = 'q';
	return ch;
}

void addpet(Tree *pt){
	Item tmp;
	if(TreeFull(pt))puts("No room in the club!");
	else {
		puts("Please enter name of pet:");
		s_gets(tmp.petname, SLEN);
		puts("Please enter pet kine:");
		s_gets(tmp.petkind, SLEN);
		uppercase(tmp.petname);
		uppercase(tmp.petkind);
		AddItem(&tmp, pt);
		
	}
}

void showpets(const Tree *pt){
	if(TreeEmpty(pt))puts("No entries!");
	else Trave(pt, printitem);

}
void printitem(Item item){
	printf("Pet:%-19s Kind: %-19s\n", item.petname, item.petkind);
}

void findpet(const Tree *pt){
	Item tmp;
	if(TreeEmpty(pt)){
		puts("No entries!");
		return ;
	}
	puts("Please enter name of pet you wish to find:");
	s_gets(tmp.petname, SLEN);
	puts("Please enter pet kind:");
	s_gets(tmp.petkind, SLEN);
	uppercase(tmp.petname);
	uppercase(tmp.petkind);
	printf("%s the %s ", tmp.petname, tmp.petkind);
	if(InTree(&tmp, pt)) printf("is a member\n");
	else printf("is not a member\n");
}

void droppet(Tree *pt){
	Item tmp;
	if(TreeEmpty(pt)){
		puts("No enteries!");
		return;
	}
	puts("Please enter name of pet you wish to delete:");
	s_gets(tmp.petname, SLEN);
	puts("Please enter pet kind:");
	s_gets(tmp.petkind, SLEN);
	uppercase(tmp.petname);
	uppercase(tmp.petkind);
	printf("%s the %s", tmp.petname, tmp.petkind);
	if(DeleteItem(&tmp, pt))printf("is dropped from the club.\n");
	else printf("is not a member\n");
}

void uppercase (char *str){
	while(*str){
		*str = toupper(*str);
		str++;
	}
}

char *s_gets(char *st, int n){

	char *retVal;
	char *find;
	retVal = fgets(st, n, stdin);
	if(retVal){
		find = strchr(st, '\n');
		if(find) *find = '\0';
		else while(getchar() != '\n')continue;
	}
	return retVal;
}
